require 'yaml'

DIR = File.dirname(__FILE__)
SOURCE_TREE_ROOT_DIR = File.join(DIR, '..', '..')
VERSION_FILE_PATH = File.join(SOURCE_TREE_ROOT_DIR, 'config' , 'application_config', 'version.yml')

namespace :deploy do
  
  desc "Deploy to staging"
  task :stg, :version do |t, args|
    version = args[:version]
    
    if not version =~ /\d+\.\d+\.\d+/
      raise "usage rake deploy:stg[version.major.minor]"
    end
    
    puts "Deploying to staging"
    
    # Update changes
    puts "Calling hg pull ..."
    ok = system("hg pull")
    puts 'Error doing hg pull' and return if not ok
    
    puts "Calling hg update ..."
    ok = system("hg update")
    puts 'Error doing hg update' and return if not ok
    
    # Tag version
    puts "Calling hg tag ..."
    ok = system("hg tag #{version}")
    puts 'Error doing hg tag' and return if not ok
    
    # Write version to file
    puts "Writing version number to version.yml ..."
    write_version_file(version)
    
    # Push changes (in order to push the tag)
    puts "Calling hg push ..."
    ok = system("hg push")
    puts 'Error doing hg push' and return if not ok
    
    # Call db:reset
    puts "Calling rake db:reset ..."
    ok = system("rake db:reset")
    puts 'Error doing rake db:reset' and return if not ok
    
    puts "Done"
  end
  
end

def write_version_file(version)
  map = {:version => version}
  File.open(VERSION_FILE_PATH, 'w') do |f|
        f.write(YAML.dump(map))
  end
end